//
//  json_demo1ViewController.m
//  json_demo1
//
//  Created by Marin Todorov on 2/24/11.
//  Copyright 2011 Marin Todorov. All rights reserved.
//

#import "json_demo1ViewController.h"
#import "JSON.h"

#define kLatestKivaLoansURL @"http://www.lemil.com.ar/apps/imegatlon/sucursales.php"

@implementation json_demo1ViewController

@synthesize responseData;

#pragma mark -
#pragma mark Fetch loans from internet
-(void)loadData
{
	self.responseData = [NSMutableData data];
	
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kLatestKivaLoansURL]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[connection release];
	self.responseData = nil;
}

#pragma mark -
#pragma mark Process loan data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
	
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	self.responseData = nil;
    
	NSArray* todasLasSucursales = [(NSDictionary*)[responseString JSONValue] objectForKey:@"sucursales"];
	[responseString release];
	
	//choose a random sucursal
	NSDictionary* unaSucursal = [todasLasSucursales objectAtIndex:0];
	
	//fetch the data
	//NSNumber* latitud = [unaSucursal objectForKey:@"latitud"];
	//NSNumber* longitud = [unaSucursal objectForKey:@"longitud"];
	NSNumber* estado = [unaSucursal objectForKey:@"estado"];
    
	NSString* nombre = [unaSucursal objectForKey:@"nombre"];
	NSString* horario = [unaSucursal objectForKey:@"horario"] ;
	NSString* direccion = [unaSucursal objectForKey:@"direccion"] ;
	
	//set the text to the label
	label.text = [NSString stringWithFormat:@"Sucursal %@ , Dirección: %@ ,  horario %@,  estado: %@",
				   nombre,direccion,horario, estado
				   ];
}

@end
